from pydantic import BaseModel, Field, validator
from typing import List, Optional, Dict, Any
from datetime import datetime
import json

class BackupTaskCreate(BaseModel):
    """创建备份任务请求模型"""
    task_name: str = Field(..., description="任务名称", example="我的文件备份")
    source_directory_ids: List[int] = Field(default=[], description="要备份的目录ID列表，空列表表示备份所有文件", example=[1, 2, 3])
    schedule_type: str = Field(default="manual", description="计划类型", example="daily")
    is_incremental: bool = Field(default=True, description="是否为增量备份", example=True)
    
    @validator('schedule_type')
    def validate_schedule_type(cls, v):
        allowed_types = ["manual", "daily", "weekly", "monthly"]
        if v not in allowed_types:
            raise ValueError(f"计划类型必须是以下之一: {', '.join(allowed_types)}")
        return v
    
    class Config:
        schema_extra = {
            "example": {
                "task_name": "我的文档备份",
                "source_directory_ids": [1, 2],
                "schedule_type": "weekly",
                "is_incremental": True
            }
        }

class BackupTaskUpdate(BaseModel):
    """更新备份任务请求模型"""
    task_name: Optional[str] = Field(None, description="任务名称", example="我的文件备份-修改")
    source_directory_ids: Optional[List[int]] = Field(None, description="要备份的目录ID列表", example=[1, 2, 3, 4])
    schedule_type: Optional[str] = Field(None, description="计划类型", example="weekly")
    is_incremental: Optional[bool] = Field(None, description="是否为增量备份", example=True)
    
    @validator('schedule_type')
    def validate_schedule_type(cls, v):
        if v is not None:
            allowed_types = ["manual", "daily", "weekly", "monthly"]
            if v not in allowed_types:
                raise ValueError(f"计划类型必须是以下之一: {', '.join(allowed_types)}")
        return v
    
    class Config:
        schema_extra = {
            "example": {
                "task_name": "我的文档备份-更新",
                "schedule_type": "monthly"
            }
        }

class BackupFileBase(BaseModel):
    """备份文件基础模型"""
    id: int
    backup_task_id: int
    file_id: int
    backup_path: str
    backup_time: datetime
    file_size: int
    is_latest: bool
    backup_type: str
    status: str
    
    class Config:
        orm_mode = True

class BackupTaskBase(BaseModel):
    """备份任务基础模型"""
    id: int
    user_id: int
    task_name: str
    backup_path: str
    status: str
    last_backup_time: Optional[datetime]
    schedule_type: str
    is_incremental: bool
    created_at: datetime
    updated_at: datetime
    total_file_count: int
    total_file_size: int
    source_directory_ids: str
    
    class Config:
        orm_mode = True
        
    @validator('source_directory_ids', pre=True)
    def parse_source_directory_ids(cls, v):
        """确保源目录ID列表为字符串形式的JSON"""
        if isinstance(v, list):
            return json.dumps(v)
        return v
        
class BackupTaskResponse(BackupTaskBase):
    """备份任务响应模型"""
    source_directories: Optional[List[Dict[str, Any]]] = None
    
    @validator('source_directory_ids', pre=False)
    def parse_json_source_directory_ids(cls, v):
        """将JSON字符串解析为实际的列表"""
        try:
            if v:
                return json.loads(v)
            return []
        except:
            return []

class BackupFileResponse(BackupFileBase):
    """备份文件响应模型"""
    file_info: Optional[Dict[str, Any]] = None

class PaginatedBackupTaskResponse(BaseModel):
    """分页备份任务响应模型"""
    items: List[BackupTaskResponse]
    total: int
    page: int
    page_size: int
    total_pages: int

class PaginatedBackupFileResponse(BaseModel):
    """分页备份文件响应模型"""
    items: List[BackupFileResponse]
    total: int
    page: int
    page_size: int
    total_pages: int 